<?php
/* ******************************
 *	Category aJax actions
 * ******************************
*/

include('../../includes/classes/core.php');
include('../../includes/classes/category.tree.class.php');

include('../../includes/classes/log.class.php');

$log 		= new log();


$action	= $_REQUEST['act'];
$error	= '';
$data	= '';

switch ($action) {
	case 'get_add_page':
		$page		= GetPage();
		$data		= array('page'	=> $page);
		
        break;
 	case 'get_list' :
		$count	= $_REQUEST['count'];
	    $hidden	= $_REQUEST['hidden'];
	    
	    $rResult = mysql_query("SELECT	  `sale_transaction`.`id`,
										  `sale_transaction`.`end_date`,
	    								  `persons`.`name`,
										  `production`.`name`,
										  `sale_transaction_detail`.`product_quantity`
								  FROM    `sale_transaction`
							 LEFT JOIN    `users` ON `users`.`id` = `sale_transaction`.`user_id`
							 LEFT JOIN    `persons` ON `persons`.`id` = `users`.`person_id`
							 LEFT JOIN    `sale_transaction_detail` ON `sale_transaction_detail`.`transaction_id` = `sale_transaction`.`id`
							 LEFT JOIN    `production` ON `production`.`id` = `sale_transaction_detail`.`production_id`
							 WHERE `sale_transaction`.`status` = 5");
	    
		$data = array(
			"aaData"	=> array()
		);
		
		while ( $aRow = mysql_fetch_array( $rResult ) )
		{
			$row = array();
			for ( $i = 0 ; $i < $count ; $i++ )
			{
				/* General output */
				$row[] = $aRow[$i];
				if($i == ($count - 1)){
					$row[] = '<input type="checkbox" name="check_' . $aRow[$hidden] . '" class="check" value="' . $aRow[$hidden] . '" />';
				}
			}
			$data['aaData'][] = $row;
		}
		
        break;
    case 'save_subtract':
    	$user_id         = $_COOKIE['USERID'];
		$id				 = $_REQUEST['id'];
    	$prod_name       = $_REQUEST['prod_name'];
    	$quantity        = $_REQUEST['qnt'];
    	$object_id       = $_REQUEST['obj_id'];
    	$prod_id         = GetProductID($prod_name);
    	
    	$check 			 =  IsProduct($prod_id);
    	$checkexists     = CheckProductionExists($prod_id, $quantity, $object_id);
    	
		
	    if($check){
	    	if($checkexists){
	    		AddSubtraction($user_id, $prod_id, $quantity, $object_id);
	    		SubtractReserve($prod_id, $quantity, $object_id);
	    	}else{
	    			$error = "მითითებული რაოდენობა აღემატება მარაგში არსებულ რაოდენობას!";
	    	}
	    }else{
	    		AddSubtraction($user_id, $prod_id, $quantity, $object_id);
	    		SubtractRecipieReserve($prod_id, $quantity, $object_id);
	    }
    	
		
        break;
		
    default:
       $error = 'Action is Null';
}

$data['error'] = $error;

echo json_encode($data);


/* ******************************
 *	subtract Functions
 * ******************************
 */

function CheckProductionExists($prod_id, $prod_quantity, $object_id){

	$check = true;

	$res = mysql_fetch_assoc(mysql_query("SELECT 	IF(SUM(reserve.quantity - reserve.sold) >= $prod_quantity, 1, 0) AS `check`
			FROM 	`reserve`
			WHERE 	reserve.object_id = $object_id && reserve.production_id = $prod_id
			GROUP 	BY reserve.object_id, reserve.production_id"));
		if($res['check']==0){
			$check = false;
		}

	return $check;
}

function AddSubtraction($user_id, $prod_id, $quantity, $object_id)
{
	$self_cost = 0;
	
	$check = IsProduct($prod_id);
	
	if($check){
		$res = mysql_fetch_assoc(mysql_query("SELECT  	pricelist.`price` AS `cost`,    
														ROUND((SELECT DISTINCT reserve.price FROM reserve WHERE reserve.production_id = production.id ),2) AS `self_cost`
												FROM    `production`
										   LEFT JOIN    pricelist ON pricelist.production_id = `production`.`id`
											   WHERE    `production`.`id` NOT IN (SELECT `recipie_id` FROM `recipie`) AND `production`.`actived` = 1 AND `production`.`id` = $prod_id"));

		$self_cost = $res['self_cost']*$quantity;
		
	}else{
		$res = mysql_fetch_assoc(mysql_query("SELECT  pricelist.`price` AS `cost`,      
													  ROUND(SUM((SELECT DISTINCT reserve.price FROM reserve WHERE reserve.production_id = rec.ingredient_id ) * rec.quantity * rec.default_amount),2)  AS `self_cost`       
											    FROM  `recipie` AS rec 
										   LEFT JOIN  `production` ON `production`.`id` = `rec`.`recipie_id`
										   LEFT JOIN  pricelist ON pricelist.production_id = `rec`.`recipie_id`
											   WHERE  `production`.`id` IN (SELECT `recipie_id` FROM `recipie`) AND `production`.`actived` = 1 AND `production`.`id` = $prod_id
											GROUP BY  rec.recipie_id"));

		$self_cost = $res['self_cost']*$quantity;
	}
	$date = date('Y-m-d H:i:s');
	
	mysql_query("INSERT INTO `sale_transaction`
	(`user_id`, `object_id`, `start_date`, `end_date`, `sum_self_cost`, `status`)
	VALUES
	($user_id, $object_id, '$date', '$date', $self_cost, 5)");
	$tr_id	= mysql_insert_id();
	
	GLOBAL $log;
	$log->setInsertLog('sale_transaction');
	
	
	
	mysql_query("INSERT INTO `sale_transaction_detail`
	(`user_id`, `transaction_id`, `production_id`, `product_quantity`, `self_cost`)
	VALUES
	($user_id, $tr_id, $prod_id, $quantity, $self_cost)");
	$log->setInsertLog('sale_transaction_detail');
}

function IsProduct($prod_id){
	$check = true;
	$result =mysql_query("SELECT      `recipie`.`recipie_id`
							FROM      `recipie`
							LEFT JOIN `pricelist` ON `pricelist`.`production_id` =`recipie`.`recipie_id` 
							WHERE 	  `recipie`.`recipie_id` = $prod_id
			 ");
	$row_number = mysql_num_rows($result);
	
	if($row_number > 0){
		$check = false;
	}
	
	return $check;
}

function SubtractRecipieReserve($prod_id, $quantity, $object){
	$res = mysql_query("SELECT  `rec`.`recipie_id` AS `id`,
								`rec`.`ingredient_id` AS `ingredient_id`,
								`rec`.`quantity`*`rec`.`default_amount` AS `quantity`
						FROM 	`recipie` AS `rec`
						WHERE  	`rec`.`recipie_id` = $prod_id");
	
	while($row = mysql_fetch_assoc($res)){
		SubtractReserve($row['ingredient_id'], $row['quantity']*$quantity, $object);
	}
	
}

function SubtractReserve($prod_id, $quantity, $object)
{
	$req_quantity = $quantity;
	$res = mysql_query("SELECT  	`reserve`.`id`,
			`reserve`.`production_id`,
			`reserve`.`object_id`,
			`reserve`.`sold`,
			`reserve`.`quantity` - `reserve`.`sold` AS `diff`,
			`reserve`.`create_date`
			FROM 		`reserve`
			WHERE 		`reserve`.`object_id` = $object && `reserve`.`production_id` = $prod_id
			ORDER BY 	`reserve`.`create_date` ASC" );
	
	while ($row = mysql_fetch_array($res)) {
		if ($req_quantity != 0) {
			if($row['diff'] > $req_quantity){
				$sum = $row['sold'] + $req_quantity;
				mysql_query("UPDATE	`reserve`
								SET	`sold` = $sum
							  WHERE	`id` = $row[id]" );
				$req_quantity = 0;
			}else if($row['diff'] == $req_quantity){
				$sum = $row['sold'] + $row['diff'];
				mysql_query("UPDATE	`reserve`
							    SET	`sold` = $sum
							  WHERE	`id` = $row[id]" );
				$req_quantity = 0;
				}else{
					$sum = $row['sold'] + $row['diff'];
					mysql_query("UPDATE	`reserve`
								 SET	 `sold` = $sum
								WHERE	`id` = $row[id]" );
					$req_quantity = $req_quantity - $row['diff'];
				}
			}
		}
}

function GetObjectList()
{
	$data = '';
	$req = mysql_query("SELECT `id`, `name`
						FROM `object`
						WHERE (`type` = 5 OR `type` = 2) AND `actived`=1");

	while( $res = mysql_fetch_assoc($req)){
		$data .= '<option value="' . $res['id'] . '">' . $res['name'] . '</option>';
	}

	return $data;
}

function GetProductID($prod_name)
{
	$prod_name = htmlspecialchars($prod_name, ENT_QUOTES);
	$res = mysql_fetch_assoc(mysql_query("	SELECT `id`
			FROM `production`
			WHERE `code` = '$prod_name' || `name` = '$prod_name'"));
	return $res['id'];
}


function GetPage($res = '')
{
	$image = $res[image];
	if(empty($image)){
		$image = '0.jpg';
	}
	
	$data = '
	<div id="dialog-form">
	    <fieldset style="width: 400px; float: left;">
	    	<legend>ძირითადი ინფორმაცია</legend>
	    	
	    	<table class="dialog-form-table">
				<tr>
					<td style="width: 100px;"><label for="obj_id">ობიექტი</label></td>
					<td>
					<select id="obj_id" class="idls">' . GetObjectList() . '</select>
					</td>
				</tr>
				<tr>
					<td style="width: 100px;"><label for="prod_name">დასახელება</label></td>
				 	<td>
						<div class="seoy-row" id="prod_name_seoy">
							<input type="text" id="prod_name" class="idle seoy-address" onblur="this.className=\'idle seoy-address\'" onfocus="this.className=\'activeField seoy-address\'" value="' . $res['name'] . '" />
							<button id="prod_name_btn" class="combobox">prod_name</button>
						</div>
					<td>
				</tr>
				<tr>
					<td style="width: 100px;"><label for="quantity">რაოდენობა</label></td>
					<td>
						<input type="text" class="idle seoy-address" onblur="this.className=\'idle seoy-address\'" onfocus="this.className=\'activeField seoy-address\'" id="quantity" value="" />
					</td>
				</tr>
			</table>
			<!-- ID -->
			<input type="hidden" id="sub_id" value="' . $res['id'] . '" />
        </fieldset>				
    </div>
    ';
	return $data;
}

?>